package org.niu.tree;

import java.util.LinkedList;
import java.util.Queue;

public class FindTilt {
    public int findTilt(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int sum = 0;
        while (!q.isEmpty()){
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = q.poll();
                int left = dfs(poll.left);
                int right = dfs(poll.right);
                sum += Math.abs(right-left);
                if(poll.left!=null){
                    q.offer(poll.left);
                }
                if(poll.right!=null){
                    q.offer(root.right);
                }
            }
        }
        return sum;
    }
    int dfs(TreeNode root){
        if(root == null) return 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int sum = root.val;
        while (!q.isEmpty()){
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = q.poll();
                sum += poll.val;
                if(poll.left!=null){
                    q.offer(poll.left);
                }
                if(poll.right!=null){
                    q.offer(root.right);
                }
            }
        }
        return sum;
    }
}
